package org.hot100_0.leetcode22;

import java.util.ArrayList;
import java.util.List;

public class Solution {

    List<String> res = new ArrayList<>();

    StringBuilder item = new StringBuilder();

    public List<String> generateParenthesis(int n) {

        backtracking(n, 0, 0);

        return res;
    }

    private void backtracking(int n, int left, int right) {

        if (item.length() == n * 2) {
            res.add(new String(item));
            return;
        }

        if (left < n) {
            item.append("(");
            left++;
            backtracking(n, left, right);

            left--;
            item.deleteCharAt(item.length() - 1);
        }

        if (right < left) {
            item.append(")");
            right++;
            backtracking(n, left, right);

            right--;
            item.deleteCharAt(item.length() - 1);
        }

    }
}
